import React from 'react'
import {connect} from 'react-redux'
import action from '../store/action/index'
import {Form, Modal, Table, Input, Spin, Radio, Tag, Divider, Button, Select, Steps, Tooltip, Icon} from 'antd';
import {
    genProjectApi,
    fetchPageProjectApi,
    addProjectApi,
    modifyProjectApi,
    exportGenConfig, getTemplateData
} from '../api/projectManager';
import {message} from "antd/lib/index";
import {fetchDatabaseListApi} from "../api/databaseManager";

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const Step = Steps.Step;
const FormItem = Form.Item;

class ProjectManager extends React.Component {

    state = {
        visible: false,
        exportVisible: false,
        loading: false,
        projectList: [],
        projectInfo: {},
        comment: "",
        exportType: "",
        templateList: [],
        databaseObj: {},
        proInfoObj: {},
        current: 0,
        databaseArr: [],
        databaseInfo: {},
        databaseList: [],
        rbacDatabaseList: [],
        butLoading: false
    }

    genProjectId;

    constructor(props, context) {
        super(props, context);
    }

    componentDidMount() {
        document.title = '项目管理';
        this.loadPageProjectList(1);

        this.getTemplateType();
        this.getDatabaseList();
    }

    getDatabaseList() {
        fetchDatabaseListApi().then(res => {
            const dbArr = res.data.data || [];
            const db = [];
            const rbacDb = [];
            for (const item of dbArr) {
                if (item.rbac == 'true') {
                    rbacDb.push(item);
                } else {
                    db.push(item)
                }
            }

            this.setState({databaseList: db, rbacDatabaseList: rbacDb});
        })
    }

    // 获取模版类型
    getTemplateType() {
        let that = this;
        //[{value:"",label:"",info:{},databaseData:[{dbName:"",},{}]},{}]
        getTemplateData().then(res => {
            // 数据处理
            const temList = [];
            const dbObj = {};
            const proObj = {}
            if (res.data && res.data.code === 10000) {
                const data = JSON.parse(res.data.data);

                for (const item of data) {
                    temList.push({value: item.value, label: item.label});
                    dbObj[item.value] = item.databaseData;
                    proObj[item.value] = item.info;
                }

                that.setState({templateList: temList, databaseObj: dbObj, proInfoObj: proObj});

            }
        })

    }


    loadPageProjectList(page) {
        var ret = fetchPageProjectApi(page, 22);
        ret.then((res) => {
            this.setState({...this.state, projectList: res.data.data});
        })
    }

    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });
    }

    showProjectInfo(pInfo) {
        console.info(JSON.stringify(pInfo));
        this.setState({...this.state, projectInfo: pInfo, visible: true})
    }

    saveBaseInfo() {
        let that = this;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);

                const {projectInfo, databaseObj} = this.state;

                this.setState({
                    projectInfo: {...projectInfo, ...values},
                    databaseArr: JSON.parse(databaseObj[values.templateType] ? databaseObj[values.templateType] : []),
                    current: this.state.current + 1
                })

                // let {id} = that.state.projectInfo;
                //
                //
                // let formData = that.props.form.getFieldsValue();
                //
                // let ret = null;
                // if (id) {
                //     formData.id = id;
                //     ret = modifyProjectApi(formData);
                // } else {
                //     ret = addProjectApi(formData);
                // }
                //
                // ret.then((res) => {
                //     message.success('保存成功！');
                //     that.setState({...that.state, projectInfo: {}, visible: false})
                //     that.loadPageProjectList(1)
                // });
            }
        });
    }

    saveProjectInfo() {
        let that = this;
        console.log(this.state.projectInfo)
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log(values);
                that.setState({databaseInfo: values, butLoading: true});

                const {projectInfo, current} = this.state;

                addProjectApi({...projectInfo, dbJson: JSON.stringify(values)}).then(res => {
                    that.setState({butLoading: false});
                    if (res.data && res.data.code === 10000) {
                        message.success("添加成功！");
                        that.setState({
                            ...that.state,
                            projectInfo: {},
                            visible: false,
                            current: 0
                        })
                    } else {
                        message.success("添加失败！");
                    }
                });
            }
        })
    }


    onChangeRadio(value) {
        this.props.form.resetFields();
        console.log(value);
        if (value === "code_template") {
            this.setState({projectInfo: {templateType: 'code_template', proType: 'simple'}, databaseArr: []})
        } else if (value === "code-microservice") {
            this.setState({projectInfo: {templateType: 'code_microservice', proType: 'micro'}, databaseArr: []})
        } else {
            const {proInfoObj, databaseObj} = this.state;
            this.setState({
                projectInfo: JSON.parse(proInfoObj[value]),
            })
        }
    }


    render() {

        let {projectList, templateList, visible, exportVisible, current, databaseArr, databaseList, rbacDatabaseList} = this.state;
        const proTypeDic = {simple: '单应用', micro: '微服务'};
        const rows = projectList.rows;

        // <Link to={{ pathname:'/projectConfig', search: `?projectId=${record.id}` }} target="_blank"></Link>

        const columns = [{
            title: 'Name',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => (
                <span>
                    <a href={`#/projectConfig?projectId=${record.id}`} target="_blank">{text}</a>
                </span>
            ),
        }, {
            title: '服务类型',
            key: 'proType',
            dataIndex: 'proType',
            render: text => <Tag color={text === 'simple' ? 'blue' : 'green'} key={text}>{proTypeDic[text]}</Tag>,

        }, {
            title: '是否生成WebUi',
            key: 'genWeb',
            dataIndex: 'genWeb',
            render: text => <Tag color={text === 'no' ? 'blue' : 'green'} key={text}>{text}</Tag>,

        }, {
            title: 'ArtifactId',
            dataIndex: 'artifactId',
            key: 'artifactId',
        }, {
            title: 'GroupId',
            dataIndex: 'groupId',
            key: 'groupId',
        }, {
            title: 'version',
            key: 'version',
            dataIndex: 'version',
            render: text => <Tag color="blue" key={text}>{text}</Tag>,

        }, {
            title: 'Action',
            key: 'action',
            render: (text, record) => (
                <span>
                    {/*<a href="javascript:;" onClick={() => {*/}
                    {/*    this.showProjectInfo(record)*/}
                    {/*}}>修改</a>*/}
                    {/*<Divider type="vertical"/>*/}
                    <a href="javascript:;" onClick={() => {

                        this.genProjectId = record.id;


                        var localPath = localStorage.getItem('genProjectLocalPath_' + this.genProjectId);


                        if (!localPath) {
                            localPath = record.localPath;
                        }

                        this.setState({
                            ...this.state,
                            genVisible: true,
                            genProjectLocalPath: localPath,
                            proType: record.proType
                        })

                    }}>生成</a>
                    <Divider type="vertical"/>
                    <a href="javascript:;" onClick={() => {

                        this.genProjectId = record.id;


                        var localPath = localStorage.getItem('genProjectLocalPath_' + this.genProjectId);


                        if (!localPath) {
                            localPath = record.localPath;
                        }

                        this.setState({
                            ...this.state,
                            exportVisible: true,
                            genProjectLocalPath: localPath,
                            comment: record.comment,
                            exportType: record.exportType
                        })

                    }}>导出配置</a>
                    <Divider type="vertical"/>
                    <a href="javascript:;">删除</a>
                </span>
            ),
        }];

        const {getFieldDecorator, getFieldValue, resetFields} = this.props.form;
        const formItemLayout = {
            labelCol: {
                sm: {span: 6},
            },
            wrapperCol: {
                sm: {span: 18},
            },
        };

        return <div>
            <Spin spinning={this.state.loading} delay={500}>
                <Button type="primary" icon="plus" onClick={() => {
                    this.showProjectInfo({templateType: 'code_template', proType: 'simple'});
                }}> 添加项目 </Button>


                {/* 项目列表 */}
                <Table columns={columns} rowKey={record => record.id} dataSource={rows}/>


                {/* 项目详情 */}
                {visible && <Modal
                    width={800}
                    title="项目详情"
                    maskClosable={false}
                    visible={visible}
                    okButtonProps={{loading: this.state.butLoading}}
                    cancelButtonProps={{loading: this.state.butLoading}}
                    okText={current === 1 ? "完成" : "下一步"}
                    onOk={() => {
                        if (current === 0) {
                            this.saveBaseInfo();
                        } else if (current === 1) {
                            this.saveProjectInfo()
                        }
                    }}
                    cancelText={current === 0 ? "取消" : "上一步"}
                    onCancel={() => {
                        if (current === 0) {
                            resetFields();
                            this.setState({...this.state, projectInfo: {}, visible: false})
                        } else {
                            this.setState({current: current - 1})
                        }

                    }}
                >
                    <div style={{marginRight: '100px', marginLeft: '100px'}}>
                        <Steps current={current}>
                            <Step title="基本信息"/>
                            <Step title="数据库选择"/>
                        </Steps>
                    </div>
                    <br/>
                    {current === 0 &&
                    <Form className={"form_item_4 form_row_small_margin"} onSubmit={this.handleSubmit}>
                        <FormItem
                            {...formItemLayout}
                            label="模版类型">
                            {getFieldDecorator('templateType', {
                                initialValue: this.state.projectInfo.templateType,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <RadioGroup onChange={(e) => this.onChangeRadio(e.target.value)}>
                                    {templateList.map(item => (
                                        <RadioButton value={item.value}>{item.label}</RadioButton>
                                    ))}

                                </RadioGroup>
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="项目名称">
                            {getFieldDecorator('name', {
                                initialValue: this.state.projectInfo.name,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Input className={"ant-col-12"}/>
                            )}
                            <span className="ant-form-text"> 项目名称(英文字母) </span>
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="项目介绍">
                            {getFieldDecorator('description', {
                                initialValue: this.state.projectInfo.description,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Input className={"ant-col-12"}/>
                            )}
                            <span className="ant-form-text"> 项目介绍 </span>
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="groupId">
                            {getFieldDecorator('groupId', {
                                initialValue: this.state.projectInfo.groupId,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Input className={"ant-col-12"}/>
                            )}
                            <span className="ant-form-text"> com.test </span>
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="artifactId">
                            {getFieldDecorator('artifactId', {
                                initialValue: this.state.projectInfo.artifactId,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Input className={"ant-col-12"}/>
                            )}
                            <span className="ant-form-text"> test_rest </span>
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="生成WebUi">
                            {getFieldDecorator('genWeb', {
                                initialValue: this.state.projectInfo.genWeb,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Radio.Group disabled={this.state.projectInfo.exportType === 'project'}
                                             className="ant-col-12">
                                    <Radio value="no">no</Radio>
                                    <Radio value="yes">yes</Radio>
                                </Radio.Group>
                            )}
                            <span className="ant-form-text"> * 生成WebUi选项不可为空</span>
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="结构">
                            {getFieldDecorator('packageType', {
                                initialValue: this.state.projectInfo.packageType,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Radio.Group className="ant-col-12"
                                             disabled={this.state.projectInfo.exportType === 'project'}>
                                    <Radio value="standard">standard</Radio>
                                    <Radio value="module">module</Radio>
                                </Radio.Group>
                            )}
                            <span className="ant-form-text"> * 结构不可为空</span>
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="项目类型">
                            {getFieldDecorator('proType', {
                                initialValue: this.state.projectInfo.proType,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Radio.Group className="ant-col-12" disabled={true}>
                                    <Radio value="micro">微服务</Radio>
                                    <Radio value="simple">单应用</Radio>
                                </Radio.Group>
                            )}
                            <span className="ant-form-text"> * 项目类型不可为空</span>
                        </FormItem>


                        <FormItem
                            {...formItemLayout}
                            label="项目版本">
                            {getFieldDecorator('version', {
                                initialValue: this.state.projectInfo.version,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Input className={"ant-col-12"}/>
                            )}
                            <span className="ant-form-text"> 项目版本 </span>
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="访问路径">
                            {getFieldDecorator('contextPath', {
                                initialValue: this.state.projectInfo.contextPath,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Input className={"ant-col-12"}/>
                            )}
                            <span className="ant-form-text"> 访问路径 </span>
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="本地路径">
                            {getFieldDecorator('localPath', {
                                initialValue: this.state.projectInfo.localPath,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Input className={"ant-col-12"}/>
                            )}
                            <span className="ant-form-text"> 生成项目本地路径 </span>
                        </FormItem>

                    </Form>}
                    {current === 1 && <>
                        <Form>
                            {databaseArr.map(val => (
                                <FormItem {...formItemLayout} label={<span>{val.label} {val.comment ?
                                    <Tooltip title={val.comment}><Icon
                                        type="question-circle-o"/></Tooltip> : ''}</span>}>
                                    {getFieldDecorator(val.value, {
                                        initialValue: this.state.databaseInfo[val.value],
                                        rules: [{
                                            required: true,
                                            message: `请选择${val.rbac == 'true' ? 'rbac' : '对应'}数据库`
                                        }],
                                    })(
                                        <Select style={{width: 270}}
                                                placeholder={`请选择${val.rbac == 'true' ? 'rbac' : '对应'}数据库`}>
                                            {(val.rbac == 'true' ? rbacDatabaseList : databaseList).map(value => (
                                                <Select.Option value={JSON.stringify({
                                                    id: value.id,
                                                    oldName: val.label
                                                })}>{value.dbName}</Select.Option>
                                            ))}
                                        </Select>
                                    )}
                                </FormItem>
                            ))}
                        </Form>

                    </>}
                </Modal>}

                {exportVisible && <Modal
                    title="导出配置"
                    visible={exportVisible}
                    okText="确定导出"
                    cancelText="关闭"
                    width={800}
                    onOk={() => {
                        const {proType} = this.state;
                        this.props.form.validateFieldsAndScroll((err, values) => {
                            if (!err) {
                                localStorage.setItem('genProjectLocalPath_' + this.genProjectId, values.localPath);
                                this.setState({...this.state, loading: true, exportVisible: false});

                                exportGenConfig({
                                    id: this.genProjectId,
                                    proType: proType,
                                    ...values
                                }).then(res => {
                                    if (res.data.code === 10000) {
                                        message.success("配置导出成功！")
                                    } else {
                                        message.error("配置导出失败！")
                                    }
                                    this.setState({...this.state, loading: false});
                                })
                            }
                        });
                    }}
                    onCancel={() => {
                        this.setState({...this.state, exportVisible: false})
                    }}
                >
                    <Form className={"form_item_4 form_row_small_margin"}>
                        <FormItem
                            {...formItemLayout}
                            label="导出类型">
                            {getFieldDecorator('exportType', {
                                initialValue: this.state.exportType,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Select style={{width: 180}} placeholder="请选择导出类型">
                                    <Select.Option value="template">模版</Select.Option>
                                    <Select.Option value="project">项目</Select.Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="项目简介">
                            {getFieldDecorator('comment', {
                                initialValue: this.state.comment,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Input className={"ant-col-12"} placeholder="用于项目模板选择"/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="导出地址">
                            {getFieldDecorator('localPath', {
                                initialValue: this.state.genProjectLocalPath,
                                rules: [{required: true, message: '不可为空'}],
                            })(
                                <Input className={"ant-col-12"} placeholder="配置导出地址"/>
                            )}
                        </FormItem>
                    </Form>
                </Modal>}

                {/* 生成地址 */}
                <Modal
                    title="生成项目-地址"
                    visible={this.state.genVisible}
                    okText="确定生成"
                    cancelText="关闭"
                    width={800}
                    onOk={() => {

                        localStorage.setItem('genProjectLocalPath_' + this.genProjectId, this.state.genProjectLocalPath);
                        this.setState({...this.state, loading: true, genVisible: false});
                        const {genProjectLocalPath, proType} = this.state;
                        genProjectApi({
                            id: this.genProjectId,
                            localPath: genProjectLocalPath,
                            proType: proType
                        }).then(res => {
                            this.setState({...this.state, loading: false});
                        })

                    }}
                    onCancel={() => {
                        this.setState({...this.state, genVisible: false})
                    }}
                >
                    <Input value={this.state.genProjectLocalPath} onChange={(e) => {
                        e.persist();
                        this.setState({...this.state, genProjectLocalPath: e.target.value});
                    }}/>
                    <br/>
                </Modal>
            </Spin>
        </div>
    }
}

// 表单控制
const _ProjectManager = Form.create()(ProjectManager);

export default connect(state => ({...state.projectManager}), action.projectManager)(_ProjectManager);
